(function($){
	var STATUS_CLOSE=1;
	var STATUS_OPEN=2;
	var gc_status=null;
	var gm_status=null;
	
	var value2Status = function(value){
		if(value==STATUS_CLOSE){
			return "未开通";
		}else if(value==STATUS_OPEN){
			return "已开通";
		}
		return "未知";
	}
	
	var value2Html = function(value,id){
		if(value==STATUS_CLOSE){
			return "开通&nbsp<span class='am-hide' id='"+id+"'><i class='am-icon-check am-icon-xs'></i></span>";
		}else if(value==STATUS_OPEN){
			return "关闭&nbsp<span class='am-hide' id='"+id+"'><i class='am-icon-check am-icon-xs'></i></span>";
		}
	}
	
	var isGcChecked = function(){
		if(!$("#gc_check").hasClass("am-hide")){
			return true;
		}
		return false;
	}
	
	var isGmChecked = function(){
		if(!$("#gm_check").hasClass("am-hide")){
			return true;
		}
		return false;
	}
	
	var buildParams4process =function(open){
	    var params ={"BODY": {"WORN_SERV_CODE": "sSmyfunc","PHONE_NO": $("#cellphone").html(),"LOGIN_NO": getEmpCode(),"PASSWORD": "0000","OPERATE_TYPE": open?"A":"D","OP_MONTH": $("#openDays").val(),"PROD_PRCID": "ACAF0024","COMMON_INFO": {"PROVINCE_GROUP": "10008"}}};
	    return params;
	};
	
	var getServiceCode =function(){
		if(isGmChecked()){
			//国漫  国漫+国长的开通关闭都是17
			return "17";
		}
		
		return "00";
	};
	
	var getService =function(){
		var service=" ";
		if(isGcChecked()){

			if(gc_status==STATUS_CLOSE){
				service+="开通";
			}else{
				service+="关闭";
			}
			service+="国长";
		}
		
		if(isGmChecked()){
			if(gm_status==STATUS_CLOSE){
				service+="开通";
			}else{
				service+="关闭";
			}
			service+="国漫";
		}
		
		return service;
		
	}
	
	
	var process = function(open){
		
		showLoadingBar($("#loadingbar"),true,false,"正在进行请求，请稍后……");
        var params = buildParams4process(open);
	  	
	 	$.ajax({
		    type: "post",
		    contentType: "application/json",
		    data: JSON.stringify(params),
		    url: Constants.rpcCrmHost+"s4000Cfm?token="+getToken(),
		    dataType: "json",
		    async: true,
		    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
		    	console.log("data = "+data);
		        console.info(data);
		        showLoadingBar($("#loadingbar"),false);
		        var service ="用户"+$("#cellphone").html()+getService();
		        if(data.ROOT.RETURN_CODE!=0){

					var msg = data.ROOT.RETURN_MSG;
					if(data.ROOT.RETURN_CODE==1005){
						var dataStr = JSON.stringify(data);
						if(dataStr.indexOf("timed out")!=-1 || dataStr.indexOf("CRM_TEMPLATE")!=-1
							|| dataStr.indexOf("中间件")!=-1 || dataStr.indexOf("系统忙")!=-1){
							msg = ("调用服务超时，请核实是否办理成功。");
						}
					}
		        	alert(service+"失败:"+msg);
		        	console.log("业务办理失败:"+data.ROOT.RETURN_CODE+":"+data.ROOT.RETURN_MSG);
		        	return;
		        }
		        //办理成功，也提示
		        alert(service+"成功！");
            saveOrder(params);
		        refresh();

		    },
		    error : function(textStatus) {
		    	alert(service+"失败！服务器没有返回。");
		        console.info("request error:");
		    }
		  });
	}

  var saveOrder = function(params) {
    params.BODY.BUSINESS_NAME = getService();
    console.log("saveOrder参数：", params);
    $.ajax({
        type: "post",
        contentType: "application/json",
        data: JSON.stringify(params),
        url: Constants.apiV2Host+"h5/order/gcgm/save",
        dataType: "json",
        async: true,
        headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
          if ('' + data.ResultCode !== '1000') {
            console.log(data.Message);
            alert("用户"+$("#cellphone").html()+getService()+"保存订单失败！");
          }
        },
        error: function(textStatus) {
          alert("用户"+$("#cellphone").html()+getService()+"保存订单失败！服务器没有返回。");
          console.info("request error:" + textStatus);
        }
    })
  }
	
	var refresh=function(){
/*		if(isGcChecked()){
			if(gc_status==STATUS_CLOSE){
				gc_status=STATUS_OPEN;
			}else{
				gc_status=STATUS_CLOSE;
			}
		}
		
		if(isGmChecked()){
			if(gm_status==STATUS_CLOSE){
				gc_status=STATUS_OPEN;
			}else{
				gm_status=STATUS_CLOSE;
			}
		}*/
		callback();
		
	}
	
	var initStepTwo = function(){
		
		$("#gc_status").html(value2Status(gc_status));
		$("#gm_status").html(value2Status(gm_status));
		
		$("#gc_submit").html(value2Html(gc_status,"gc_check"));
		$("#gm_submit").html(value2Html(gm_status,"gm_check"));
		
		hide($("#request_open"));
		hide($("#request_close"));
	}
	
	var showStatus = function(data){
		gc_status = null;
		gm_status = null;
		
		for ( var i = 0; i < data.length; i++)
	    {
			if(data[i].PROD_PRC_NAME=="国际直拨"){
				if(data[i].STATE=="Y"){
					gc_status = STATUS_OPEN;
				}else{
					gc_status = STATUS_CLOSE;
				}
			}
			else if(data[i].PROD_PRC_NAME=="国际漫游"){
				if(data[i].STATE=="Y"){
					gm_status = STATUS_OPEN;
				}else{
					gm_status = STATUS_CLOSE;
				}
			}
			
	    }
		
		if((gc_status==null)||(gm_status==null)){
			alert("获取当前用户国长国漫状态错误！");
			return;
		}
		
		
		initStepTwo();

		
    	
 
	}
	
	
	
var buildParams =function(){
	    var params ={"BODY": {"WORN_SERV_CODE": "sSpecialList","LOGIN_NO":getEmpCode(),"PHONE_NO":$("#phone").val(),"PROD_PRCID": "01","COMMON_INFO": { "PROVINCE_GROUP": "10008"}}};
	    return params;
};
	
	
var loadStatus = function(){
	  	var params = buildParams();
	  	
	 	$.ajax({
		    type: "post",
		    contentType: "application/json",
		    data: JSON.stringify(params),
		    url: Constants.rpcCrmHost+"sUserOrdQry?token="+getToken(),
		    dataType: "json",
		    async: true,
		    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
		    	console.log("data = "+data);
		        console.info(data);
		        if(data.ROOT.RETURN_CODE!=0){
		        	alert(data.ROOT.RETURN_MSG);
		        	console.log("获取RPC基本信息接口返回失败！code:"+data.ROOT.RETURN_CODE);
		        	return;
		        }
		        
		        if(data.ROOT.OUT_DATA.PRC_INFO_LIST.length<=0){
		        	alert("接口返回数据有误！");
		        	return;
		        }
		        
		        showStatus(data.ROOT.OUT_DATA.PRC_INFO_LIST);
		    },
		    error : function(textStatus) {
		    	alert("获取业务状态失败！服务器没有返回。");
		        console.info("request error:");
		    }
		  });
};


var callback=function(){
	//$("#phone").val("13890355933");
	//$("#phone").val("13608080147");
  	loadStatus();
	hide($("#step_one"));
	$("#cellphone").html($("#phone").val());
	show($("#step_two"));
}
	
$(function(){
    	
    	($("#getSMS")).on("click",function(){
    		sendSms($("#phone").val());
    	});
    	
    	($("#validate")).on("click",function(){
    		verifySms($("#phone").val(),$("#smscode").val(),callback);
    	});
    	
    	
    	($("#gc_submit")).on("click",function(){
    		//alert("xxx");
			if(isGmChecked()){
				if(gm_status!=gc_status){
					alert("不能同时同时办理开通和关闭");
					return;
				}
			}
    		if($("#gc_check").hasClass("am-hide")){
    			$("#gc_check").removeClass("am-hide");
    			if(gc_status==STATUS_CLOSE){
    				//去开通
            		show($("#request_open"));
            		hide($("#request_close"));
        		}else if(gc_status==STATUS_OPEN){
        			//去关闭
        			hide($("#request_open"));
        			if(!isGmChecked()){
        				$("#close").html("点击关闭国际直拨业务");
        			}else{
        				if(gm_status==STATUS_OPEN){
        					$("#close").html("点击关闭国长国漫业务");
        				}
        			}
/*        			
       		    	($("#close")).on("click",function(){
    		    		process(false);
    		    	});*/
       		    	
            		show($("#request_close"));
            		
        		}
    		}
    		else{
    			//取消
    			$("#gc_check").addClass("am-hide");
    			if(!isGmChecked()){
    			  hide($("#request_open"));
        		  hide($("#request_close"));
    			}
    		}
    		

    	});
    	
    	($("#gm_submit")).on("click",function(){
    	
			if(isGcChecked()){
				if(gc_status!=gm_status){
				    alert("不能同时同时办理开通和关闭");
					return;
				}
			}
			
    		if($("#gm_check").hasClass("am-hide")){
  			   $("#gm_check").removeClass("am-hide");
    			if(gm_status==STATUS_CLOSE){
    			   //去开通
                   show($("#request_open"));
                   hide($("#request_close"));	

        		}else if(gm_status==STATUS_OPEN){
        			//去关闭
        			hide($("#request_open"));
        			if(!isGcChecked()){
        				$("#close").html("点击关闭国际漫游业务");
        			}else{
        				if(gc_status==STATUS_OPEN){
        					$("#close").html("点击关闭国长国漫业务");
        				}
        			}
        			
/*     		    	($("#close")).on("click",function(){
    		    		process(false);
    		    	});*/
        			
            		show($("#request_close"));
        		}
    		}
    		else{
    			//取消
    			$("#gm_check").addClass("am-hide");
    			if(!isGcChecked()){
        			hide($("#request_open"));
            		hide($("#request_close"));
    			}

    		}
    	});
    	
    	($("#confirmOpen")).on("click",function(){
    		 if(isGcChecked()&&!isGmChecked()){
    			 //选择开通国长，国长未开通的情况，直接请求,开通
    			 process(true);
    			 return;
    		 }
    		 else if(isGmChecked()){
    			 if(isGcChecked()){
    				 //两种都没有开通，选择去开通两种
    				 $("#modal_msg").html("是否同时开通国际直拨和国际漫游业务"); 
    	         }else{
    	        	 if(gc_status==STATUS_CLOSE){
    	        		 //国长未开通，选择开通国漫，提示两种一起开通
    	        		 $("#modal_msg").html("开通国际漫游业务必须同时开通国际直拨业务，是否确定开通"); 
    	        	 }else{
    	        		 //国长已开通，选择开通国漫，直接请求开通国漫
    	        		 process(true);
    	        		 return;
    	        	 }
    	        	
    	         }
    			
    		 }
	       	
	         $('#myConfirm').modal({
	          relatedTarget: this,
	          onConfirm: function(options) {
	        	  //直接请求
	        	  process(true);
	          },
	          onCancel: function() {
	            //alert('算求，不弄了');
	          }
	        });
	         
    	});
    	
    	
    	($("#cancel")).on("click",function(){
    		initStepTwo();
    	});
    	
		
	   ($("#close")).on("click",function(){
    		process(false);
    	});
    	
    	//callback();
  
  	
    });
  


})(jQuery);